package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
)

var PREFIX = "72b4a9_zihuanke/2016"

func main() {
	endpoint := "127.0.0.1:9000"
	accessKeyID := "minioadmin"
	secretAccessKey := "minioadmin"
	useSSL := false

	// Initialize minio client object.
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: useSSL,
	})
	if err != nil {
		fmt.Println(err)
	}

	log.Printf("%#v\n", minioClient) // minioClient is now set up

	ctx, cancel := context.WithCancel(context.Background())

	defer cancel()

	objectCh := minioClient.ListObjects(ctx, "docs", minio.ListObjectsOptions{
		Prefix:    PREFIX,
		Recursive: true,
	})
	for object := range objectCh {
		if object.Err != nil {
			fmt.Println(object.Err)
			return
		}
		fmt.Println(object.Key)
		backupObject(minioClient, object.Key)
	}
}

func backupObject(minioClient *minio.Client, key string) {
	newName := strings.Replace(key, PREFIX, "", -1)
	newKey := "./backup/" + strings.Replace(PREFIX, "/", "_", -1) + newName
	err := minioClient.FGetObject(context.Background(), "docs", key, newKey, minio.GetObjectOptions{})
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Backup object:", key, "to", newKey)
	}
}
